/**
 * 
 */
package us.gaaoc.framework.webapp.backingbeans.clerk;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import us.gaaoc.framework.model.CourtHearingNegotiations;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.util.Messages; 
/**
 * @author Sukhada
 * 
 */
@SuppressWarnings("unchecked")
public class RejectCourtDateConfirmationPage extends BaseBackingBean {
	
	/**
	 * Properties
	 */
	
	/** Generated Serial Version UID */
	private static final long serialVersionUID = -8299240842519393179L;
	private Date clerkProposedCourtDate;
	private UIInput courtDateInput;	
	private FacesMessage message;
	private CourtHearingNegotiations courtHearingNegotiations;
	private Date scheduledCourtDate;
	private Date proposedCourtDate;	
	private String caseUuid;
	private String docketID;
	
	/**
	 * Constructor
	 *
	 */
	public RejectCourtDateConfirmationPage() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
		this.setCaseUuid((String)sessionMap.get("caseUuid"));
		this.setCourtHearingNegotiations(this.getModelFacade().findCourtHearingNegotiationsByCaseRecordUuid(this.getCaseUuid()));
		this.setProposedCourtDate(this.getCourtHearingNegotiations().getProposedCourtDate());
		this.setScheduledCourtDate(this.getCourtHearingNegotiations().getPreviousCourtDate());
		this.setDocketID(this.getModelFacade().findCaseRecordById(this.getCaseUuid(), courtUuid).getCaseTrackingId());
	}

	/**
	 * @return Returns the courtDateInput.
	 */
	public UIInput getCourtDateInput() {
		return courtDateInput;
	}

	/**
	 * @param courtDateInput
	 *            The courtDateInput to set.
	 */
	public void setCourtDateInput(UIInput courtDateInput) {
		this.courtDateInput = courtDateInput;
	}

	/**
	 * @return Returns the clerkProposedCourtDate.
	 */
	public Date getClerkProposedCourtDate() {
		return clerkProposedCourtDate;
	}

	/**
	 * @param clerkProposedCourtDate
	 *            The clerkProposedCourtDate to set.
	 */
	public void setClerkProposedCourtDate(Date clerkProposedCourtDate) {
		this.clerkProposedCourtDate = clerkProposedCourtDate;
	}

	/**
	 * This method gets called when the clerk rejects the Negotiation date
	 * @return String
	 */

	public String yes() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String caseRecordUuid = (String)sessionMap.get("caseUuid");
		Person updatePerson = (Person) sessionMap.get("person");
		String updatePersonUuid = updatePerson.getUuid();
		
		// TODO Need to allow the reason to be entered by the user of the system
		
		GregorianCalendar scheduleDate = new GregorianCalendar();
		GregorianCalendar proposedDate = new GregorianCalendar();
		GregorianCalendar newProposedDate = new GregorianCalendar();
		
		scheduleDate.setTime(this.getScheduledCourtDate());
		proposedDate.setTime(this.getProposedCourtDate());
		newProposedDate.setTime(this.getClerkProposedCourtDate());
		
		try {
			String  emailToAgent = "tapshals@gaaoc.us";
			String emailToLegalPrepror = "mcelratr@gaaoc.us";
			this.sendEmailNotification(emailToAgent, emailToLegalPrepror);
		} catch (Exception e) {			
			e.printStackTrace();
		} 

		this.getModelFacade().updateCourtDate(caseRecordUuid,this.getClerkProposedCourtDate(), updatePersonUuid);		
		this.getModelFacade().updateCourtHearingNegotiationStausToRejected(this.getCourtHearingNegotiations());
		// b7006e6c-695c-11dd-945f-00301b45ff56
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		
		
		return "gotoCaseDetailsPage";
	}
	
	/**
	 * This method navigates user to the previous page (Case Details Page)
	 * @return String
	 */
	public String back() {
		return "gotoCaseDetailsPage";
	}
	
	/**
	   * Validator for the dateOfService date.
	   * @param context FacesContext
	   * @param component UIComponent
	   * @param value Object
	   * @throws ValidatorException
	   * @throws Exception
	   */

	  public void validateDate( FacesContext context,
	                                     UIComponent component,
	                                     Object value ) throws ValidatorException,
	      Exception {
	    java.util.Date newValue = ( java.util.Date ) value;
	    
	    /* There is  a bug in jsf page to pass over a date value, 
	     * the passed value is always 1 day behind .
	     * The day field of the Calendar object
	     * starts with 1 but the month field starts with 0. This confusion
	     * might be the cause of the bug.
	     */
	    Calendar c = new GregorianCalendar();
	    c.setTime(newValue);
	    
	    System.out.println("Month = " + c.get(Calendar.MONTH)  );
	    System.out.println("Date = " + c.get(Calendar.DATE));
	    
	    int date = c.get(Calendar.DATE);
	    c.set(Calendar.DATE, date+1);
	    newValue = c.getTime();
	    
	    if ( !isValidDate( newValue ) ) {
	      message.setSeverity( FacesMessage.SEVERITY_ERROR );
	      throw new ValidatorException( message );
	    }
	  }

	  /**
	   * Utiltiy method to validate date.
	   *
	   * true if the new entered date is either equal to current date or a future date.
	   * @param value Date
	   * @return boolean
	   */
	  protected boolean isValidDate( java.util.Date value ) throws
	      Exception {
	    boolean validField = false;	   	 
        if (value.compareTo(DateUtil.getCurrentDate())<0){
        	validField = false;
  	      message = Messages.getMessage(
  		          "us.gaaoc.framework.webapp.util.errorMessage",
  		          "incorrectDate", null);
  		      message.setDetail( message.getDetail() );
  		      message.setSeverity( FacesMessage.SEVERITY_ERROR );
        }else{  
	      validField = true;
	    }
	    return validField;
	  }

  /**
   * Getter for property caseUuid
   * @return caseUuid
   */
	public String getCaseUuid() {
		return caseUuid;
	}

	/**
	 * Setter for property caseUuid
	 * @param caseUuid
	 */
	public void setCaseUuid(String caseUuid) {
		this.caseUuid = caseUuid;
	}

	/**
	 * Getter for property courtHearingNegotiations
	 * @return courtHearingNegotiations
	 */
	public CourtHearingNegotiations getCourtHearingNegotiations() {
		return courtHearingNegotiations;
	}

	/**
	 * Setter for property courtHearingNegotiations
	 * @param courtHearingNegotiations
	 */
	public void setCourtHearingNegotiations(
			CourtHearingNegotiations courtHearingNegotiations) {
		this.courtHearingNegotiations = courtHearingNegotiations;
	}

	/**
	 * Getter for property docketID
	 * @return docketID
	 */
	public String getDocketID() {
		return docketID;
	}

	/**
	 * Setter for property docketID
	 * @param docketID
	 */
	public void setDocketID(String docketID) {
		this.docketID = docketID;
	}

	/**
	 * Getter for property proposedCourtDate
	 * @return
	 */
	public Date getProposedCourtDate() {
		return proposedCourtDate;
	}

	/**
	 * Setter for property proposedCourtDate
	 * @param proposedCourtDate
	 */
	public void setProposedCourtDate(Date proposedCourtDate) {
		this.proposedCourtDate = proposedCourtDate;
	}

	/**
	 * Getter for property scheduledCourtDate
	 * @return scheduledCourtDate
	 */
	public Date getScheduledCourtDate() {
		return scheduledCourtDate;
	}

	/**
	 * Setter for property scheduledCourtDate
	 * @param scheduledCourtDate
	 */
	public void setScheduledCourtDate(Date scheduledCourtDate) {
		this.scheduledCourtDate = scheduledCourtDate;
	}
	
	private void sendEmailNotification(String emailToAgent, String emailToLegalPrepror) throws Exception {
		DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
		// GregorianCalendar calendar = new GregorianCalendar();
		// put Attorney's e-mail id
		//String emailToAgent = "mcelratr@gaaoc.us";
		//String emailToCourt = "tapshals@gaaoc.us";
		String subject = "Filing Notification";
		String message = "The File is ready to review on date "
				+ format.format(DateUtil.getCurrentDate()) + ".";

		/*
		EmailController emailController = new EmailController();
		 emailController.send(emailToAgent, "OCSS_Attorney@gaaoc.us", subject,
		 message);
		 emailController.send(emailToLegalPrepror, "OCSS_Attorney@gaaoc.us", subject,
		 message);
		*/
	}
}
